<?php

class News_Cat extends MX_Controller {

    function __construct() {
        parent::__construct();
        if (!modules::run('auth/auth/has_permission', array('operation' => OPERATION_MANAGE)))
            redirect('/');
        if (!$this->phpsession->get("news_cat_lang"))
            $this->phpsession->save('news_cat_lang', 'vi');
    }

    function dispatcher($method = NULL, $para1 = NULL, $para2 = NULL) {
        $menu_params = array('current_menu' => '/' . $this->uri->uri_string());
        $layout = 'powercms/admin_layout';
        $current_url = '/dashboard/pages';

        $lang = switch_language($para1);

        switch ($method) {
            case 'list_cat' :
                $this->output->link_js('/powercms/scripts/jquery/ui.sortable.js');
                $this->output->javascripts('setup_moveable();');
                $main_content = $this->list_cat(array('lang' => $lang, 'page' => $para2));
                $this->phpsession->save('news_cat_lang', $lang);
                break;
            case 'add_cat' :
                $main_content = $this->add_cat();
                break;
            case 'edit_cat' :
                $main_content = $this->edit_cat();
                break;
            case 'delete_cat' :
                $main_content = $this->delete_cat();
                break;
            case 'list_home_cat' :
                $this->output->link_js('/powercms/scripts/jquery/ui.sortable.js');
                $this->output->javascripts('setup_moveable();');
                $main_content = $this->list_home_cat(array('lang' => $lang, 'page' => $para2));
                $this->phpsession->save('news_cat_lang', $lang);
                break;
        }

        $view_data = array();
        $view_data['url'] = isset($current_url) ? $current_url : '';
        $view_data['admin_menu'] = modules::run('menus/menus/get_dashboard_menus', $menu_params);
        $view_data['main_content'] = $main_content;
        $view_data['title'] = $this->_title;
        $this->load->view($layout, $view_data);
    }

    public function list_cat($options = array()) {
        $view_data = array();
        $view_data['categories'] = $this->news_categories_model->get_categories_object_array_by_parent_id(array('parent_id' => ROOT_CATEGORY_ID, 'lang' => $options['lang']));
        if (isset($options['error']))
            $view_data['options'] = $options;
        $view_data['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $options['lang'], 'extra' => 'onchange="javascript:change_lang();"'));
        $view_data['lang'] = $options['lang'] != 'vi' ? '/' . $options['lang'] : '';
        //header
        $extra = array();
        $extra['lang'] = $view_data['lang'];
        $extra['categories'] = $this->news_categories_model->get_categories(array('parent_id' => 0, 'lang' => $options['lang']));
        $extra['parent_id'] = 0;
        $list_cat = "<ul>";
        $list_cat .= $this->_visit($extra);
        $list_cat .= "</ul>";
        $view_data['list_cat'] = $list_cat;
        $this->_title = 'Danh mục tin tức' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('cat/list_cat', $view_data, TRUE);
    }
    
    public function list_home_cat($options = array()) {
        $view_data = array();
        $view_data['categories'] = $this->news_categories_model->get_cat_homepage(array('lang' => $options['lang']));
        if (isset($options['error']))
            $view_data['options'] = $options;
        $view_data['lang'] = $options['lang'] != 'vi' ? '/' . $options['lang'] : '';
        $this->_title = 'Danh mục tin tức' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('cat/list_cat_home', $view_data, TRUE);
    }

    private function _visit($options = array()) {
        $output = '';
        $sub_cat = $this->_get_sub_cat($options);
        foreach ($sub_cat as $cat) {
            $has_child = $this->news_categories_model->get_categories(array('parent_id' => $cat->id));
            $style = $cat->parent_id == 0 ? 'odd' : 'even';
            $uri = $options['lang'] . '/' . url_title($cat->category, 'dash', TRUE) . '-n' . $cat->id;
            $link = 'href="javascript:void(0);" onclick="show_sub_cat(' . $cat->id . ');"';
            $show_homepage_status = $cat->show_home == SHOW_HOMEPAGE_NEWS ? 'checked' : '';
            $parent_cat = $this->news_categories_model->get_categories(array('id' => $cat->parent_id, 'last_row' => 1));
            $output .= '<li id="id_' . $cat->id . '">';
            $output .= '<div class="title_cat"><a '.$link. '> ' . $cat->category . '</a></div>';
            $output .= '<div class="cat_url">' . $uri . '</div>';
            $output .= '<div class="show_homepage"><input type="checkbox" name="show_homepage" ' . $show_homepage_status . ' onchange="change_show_cat_homepage(' . $cat->id . ');"></div>';
            $output .= '<div class="cat_panel">';
            $output .= '<a class="edit" title="Sửa danh mục bài viết này" href="javascript:void(0);" onclick="submit_news_cat(' . $cat->id . ',' . " 'edit'" . ');"><em>&nbsp;</em></a>';
            $output .= '<a class="del" title="Xóa danh mục bài viết này" href="javascript:void(0);" onclick="submit_news_cat(' . $cat->id . ',' . " 'delete' " . ');"><em>&nbsp;</em></a>';
            $output .= '</div>';
            if (count($has_child) > 0 ){
            $options['categories'] = $this->news_categories_model->get_categories(array('parent_id' => $cat->id));
            $output .= '<ul id="sub_cat_' . $cat->id . '" style="display: none;">';
            $options['parent_id'] = $cat->id;
            $output .= $this->_visit($options);
            $output .= '</ul></li>';
            }
            else {
            $output .= '</li>';    
            }
        }
        return $output;
    }

    private function _get_sub_cat($options = array()) {
        $cats = $options['categories'];
        $sub_cat = array();
        foreach ($cats as $index => $cat) {
            if ($cat->parent_id == $options['parent_id'])
                $sub_cat[$index] = $cat;
        }
        return $sub_cat;
    }

    public function add_cat() {
        $this->output->link_js('/powercms/scripts/colorpicker/js/colorpicker.js');
        $this->output->link_css('/powercms/scripts/colorpicker/css/colorpicker.css');
        $this->output->javascripts('setup_colorpicker();');
        $options = array();

        if ($this->is_postback()) {
            if (!$this->_do_add_cat())
                $options['error'] = validation_errors();
        }
        $view_data = array();
        $view_data = $this->_get_add_cat_form_data();

        if (isset($options['error']))
            $view_data['options'] = $options;

        $view_data['header'] = 'Thêm danh mục tin tức mới';
        $view_data['button_name'] = 'Thêm danh mục';
        $view_data['submit_uri'] = '/dashboard/news/categories/add';

        //header
        $this->_title = 'Thêm danh mục tin tức' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('cat/add_cat_form', $view_data, TRUE);
    }

    private function _get_add_cat_form_data() {
        $view_data = array();
        $view_data['category'] = $this->input->post('category');
        $view_data['summary'] = $this->input->post('summary');
        $view_data['bg_color'] = $this->input->post('bg_color');
        $view_data['meta_title'] = $this->input->post('meta_title');
        $view_data['meta_keywords'] = $this->input->post('meta_keywords');
        $view_data['meta_description'] = $this->input->post('meta_description');
        // 25-2-2013 : @dzung.tt : update layout cho categories
        $view_data['page_layout'] = $this->input->post('page_layout'); //layout toàn trang
        $view_data['detail_layout'] = $this->input->post('detail_layout'); //layout danh sách tin của categories
        $view_data['item_layout'] = $this->input->post('item_layout'); //layout của tin tức trong category đó
        if ($this->is_postback()) {
            $view_data['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $this->input->post('lang', TRUE), 'extra' => 'onchange="javascript:get_categories_by_lang();"'));
            $view_data['categories_combobox'] = $this->news_categories_model->
                    get_categories_combo(array('categories_combobox' =>
                $this->input->post('categories_combobox')
                , 'is_add_edit_cat' => TRUE
                , 'lang' => $this->input->post('lang', TRUE)
            ));
        } else {
            $view_data['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $this->phpsession->get('news_cat_lang'), 'extra' => 'onchange="javascript:get_categories_by_lang();"'));
            $view_data['categories_combobox'] = $this->news_categories_model->
                    get_categories_combo(array('categories_combobox' =>
                $this->input->post('categories_combobox')
                , 'is_add_edit_cat' => TRUE
                , 'lang' => $this->phpsession->get('news_cat_lang')
            ));
        }
        $view_data['scripts'] = $this->_get_scripts();
        return $view_data;
    }

    private function _do_add_cat() {
        $this->form_validation->set_rules('category', 'Tên loại', 'trim|required|xss_clean|max_length[256]');
        if ($this->form_validation->run()) {
            $data = array(
                'category' => strip_tags($this->input->post('category')),
                'summarys' => $this->input->post('summary'),
                'bg_color' => $this->input->post('bg_color'),
                'parent_id' => $this->input->post('categories_combobox') == DEFAULT_COMBO_VALUE ? ROOT_CATEGORY_ID : $this->input->post('categories_combobox'),
                'meta_title' => $this->input->post('meta_title', TRUE),
                'meta_keywords' => $this->input->post('meta_keywords', TRUE),
                'meta_description' => $this->input->post('meta_description', TRUE),
                // 25-2-2013 : @dzung.tt : update layout cho categories
                'meta_title' => $this->input->post('page_layout'),
                'meta_keywords' => $this->input->post('detail_layout'),
                'meta_description' => $this->input->post('item_layout'),
                'lang' => $this->input->post('lang', TRUE) == 0 ? 'vi' : $this->input->post('lang', TRUE)
            );
            if ($this->input->post('categories_combobox') == DEFAULT_COMBO_VALUE) {
                $categories = $this->news_categories_model->get_categories(array('parent_id' => ROOT_CATEGORY_ID,
                    'last_row' => TRUE));
            } else {
                $categories = $this->news_categories_model->get_categories(array('parent_id' => $this->input->post('categories_combobox'),
                    'last_row' => TRUE));
            }
            $data['position'] = is_object($categories) ? $categories->position + 1 : 1;
            $data['url_images'] = $this->upload_thumbnails();
            $this->news_categories_model->add_category($data);

            redirect('/dashboard/news/categories/' . $this->phpsession->get('news_cat_lang'));
        }
        return FALSE;
    }

    public function edit_cat() {
        $this->output->link_js('/powercms/scripts/colorpicker/js/colorpicker.js');
        $this->output->link_css('/powercms/scripts/colorpicker/css/colorpicker.css');
        $this->output->javascripts('setup_colorpicker();');
        $options = array();

        if ($this->is_postback() && !$this->input->post('from_list')) {
            if (!$this->_do_edit_cat())
                $options['error'] = validation_errors();
        }
        $view_data = array();
        $view_data = $this->_get_edit_cat_form_data();

        if (isset($options['error']))
            $view_data['options'] = $options;

        $view_data['header'] = 'Sửa danh mục tin tức';
        $view_data['button_name'] = 'Sửa danh mục';
        $view_data['submit_uri'] = '/dashboard/news/categories/edit';

        //header
        $this->_title = 'Sửa danh mục tin tức' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('cat/add_cat_form', $view_data, TRUE);
    }

    private function _get_edit_cat_form_data() {
        $cat_id = $this->input->post('cat_id');

        if ($this->input->post('from_list')) {
            $categories = $this->news_categories_model->get_categories(array('id' => $cat_id));
            $category = $categories->category;
            $summary = $categories->summarys;
            $bg_color = $categories->bg_color;
            $parent_id = $categories->parent_id;
            $meta_title = $categories->meta_title;
            $meta_keywords = $categories->meta_keywords;
            $meta_description = $categories->meta_description;
            // 25-2-2013 : @dzung.tt : update layout cho categories
            $page_layout = $categories->page_layout;
            $detail_layout = $categories->detail_layout;
            $item_layout = $categories->item_layout;
            $lang = $categories->lang;
            $thumbnail = $categories->url_images;
        } else {
            $category = $this->input->post('category');
            $summary = $this->input->post('summary');
            $bg_color = $this->input->post('bg_color');
            $parent_id = $this->input->post('categories_combobox');
            $meta_title = $this->input->post('meta_title');
            $meta_keywords = $this->input->post('meta_keywords');
            $meta_description = $this->input->post('meta_description');
            // 25-2-2013 : @dzung.tt : update layout cho categories
            $page_layout = $categories->page_layout;
            $detail_layout = $categories->detail_layout;
            $item_layout = $categories->item_layout;
            $lang = $this->input->post('lang');
            $thumbnail = $categories->url_images;
        }
        $view_data = array();

        $view_data['cat_id'] = $cat_id;
        $view_data['category'] = $category;
        $view_data['summary'] = $summary;
        $view_data['bg_color'] = $bg_color;
        $view_data['categories_combobox'] = $this->news_categories_model->get_categories_combo(array('categories_combobox' => $parent_id, 'lang' => $lang, 'is_add_edit_cat' => TRUE));
        $view_data['meta_title'] = $meta_title;
        $view_data['meta_keywords'] = $meta_keywords;
        $view_data['meta_description'] = $meta_description;
        // 25-2-2013 : @dzung.tt : update layout cho categories
        $view_data['page_layout'] = $page_layout;
        $view_data['detail_layout'] = $detail_layout;
        $view_data['item_layout'] = $item_layout;
        $view_data['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $lang, 'extra' => 'onchange="javascript:get_categories_by_lang();"'));
        $view_data['thumbnail'] = $thumbnail;
        $view_data['scripts'] = $this->_get_scripts();
        return $view_data;
    }

    private function _do_edit_cat() {
        $this->form_validation->set_rules('category', 'Tên loại', 'trim|required|xss_clean|max_length[256]');
        if ($this->form_validation->run()) {
            $data = array(
                'id' => $this->input->post('cat_id'),
                'category' => $this->input->post('category', TRUE),
                'summarys' => $this->input->post('summary', TRUE),
                'bg_color' => $this->input->post('bg_color', TRUE),
                'parent_id' => $this->input->post('categories_combobox'),
                'meta_title' => $this->input->post('meta_title', TRUE),
                'meta_keywords' => $this->input->post('meta_keywords', TRUE),
                'meta_description' => $this->input->post('meta_description', TRUE),
                // 25-2-2013 : @dzung.tt : update layout cho categories
                'meta_title' => $this->input->post('page_layout'),
                'meta_keywords' => $this->input->post('detail_layout'),
                'meta_description' => $this->input->post('item_layout'),
                'lang' => $this->input->post('lang', TRUE) == 0 ? 'vi' : $this->input->post('lang', TRUE)
            );
            $thumbnail = $this->upload_thumbnails();
            if ($thumbnail != NULL) {
                $data['url_images'] = $thumbnail;
                $categories = $this->news_categories_model->get_categories(array('id' => $data['id'],
                    'lang' => $data['lang'],
                    'last_row' => TRUE
                ));
                if ($categories->url_images != '' && $categories->url_images != NULL)
                    if (file_exists('./images/news_categories/' . $categories->url_images))
                        unlink('./images/news_categories/' . $categories->url_images);
            }
            $this->news_categories_model->update_category($data);

            redirect('/dashboard/news/categories/' . $this->phpsession->get('news_cat_lang'));
        }
        return FALSE;
    }

    public function delete_cat() {
        if ($this->is_postback()) {
            $cat_id = $this->input->post('cat_id');
            $categories = $this->news_categories_model->get_categories(array('parent_id' => $cat_id));
            if (count($categories) == 0) {
                $cat = $this->news_categories_model->get_categories(array('id' => $cat_id, 'last_row' => TRUE));
                if ($cat->url_images != '' && $cat->url_images != NULL)
                    if (file_exists('./images/news_categories/' . $cat->url_images))
                        unlink('./images/news_categories/' . $cat->url_images);
                $this->news_categories_model->delete_category($cat_id);
                redirect('/dashboard/news/categories/' . $this->phpsession->get('news_cat_lang'));
            }
            else {
                $options['error'] = 'Không thể xóa danh mục này vì vẫn còn các danh mục con';
                $options['lang'] = $this->_lang;
            }
        }
        return $this->list_cat($options);
    }

    function get_categories_by_lang() {
        $lang = $this->input->post('lang', TRUE);
        if (!$this->input->post('is_add_edit'))
            echo $this->news_categories_model->get_categories_combo(array('lang' => $lang));
        else
            echo $this->news_categories_model->get_categories_combo(array('lang' => $lang, 'is_add_edit_cat' => TRUE));
    }

    function upload_thumbnails() {
        $config = array();
        $config['upload_path'] = './images/news_categories/';
        $config['allowed_types'] = 'png|jpg|jpeg|gif';
        $config['max_size'] = '1024';
//        $config['width'] = 800;
//        $config['height'] = 600;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload()) {
//                return $this->upload->display_errors();
            return NULL;
        } else {
            $data = $this->upload->data();

            $this->load->library('image_lib');
            $config['image_library'] = 'gd2';
            $config['source_image'] = './images/news_categories/' . $data['file_name'];
            $config['maintain_ratio'] = TRUE;
            $config['width'] = 243;
            $config['height'] = 156;
            $config['new_image'] = './images/news_categories/thumbnails/' . $data['file_name'];
            $this->image_lib->initialize($config);
            $this->image_lib->resize();

            return $data['file_name'];
        }
    }

    private function _get_scripts() {
        $scripts = '<script type="text/javascript" src="/powercms/scripts/tiny_mce/tiny_mce.js?v=20111006"></script>';
        $scripts .= '<script language="javascript" type="text/javascript" src="/powercms/scripts/tiny_mce/plugins/imagemanager/js/mcimagemanager.js?v=20111006"></script>';
        $scripts .= '<script type="text/javascript">enable_advanced_wysiwyg("wysiwyg");</script>';
        return $scripts;
    }

    public function sort_categories() {
        $arr = $this->input->post('id');
        $category = $this->news_categories_model->get_categories(array('id' => $arr[0]));
        $i = 1;
        foreach ($arr as $recordidval) {
            $array = array('position' => $i);
            $this->db->where('id', $recordidval);
//            $this->db->where('parent_id', $category[0]->parent_id);
            $this->db->update(NEWS_CATEGORIES, $array);
            $i = $i + 1;
        }
    }
    
    public function sort_categories_home() {
        $arr = $this->input->post('id');
        $category = $this->news_categories_model->get_cat_homepage(array('id' => $arr[0]));
        $i = 1;
        foreach ($arr as $recordidval) {
            $array = array('position' => $i);
            $this->db->where('id', $recordidval);

            $this->db->update(CAT_HOME, $array);
            $i = $i + 1;
        }
    }

}

